package com.bm.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;

public class YoudaoWordGenerator {

    public static void onestepget(String selectionValue) {
        try {
            // 设置URL
            String url = "https://dict.youdao.com/jsonapi?q=" + selectionValue;

            // 创建URL对象并打开连接
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为GET
            con.setRequestMethod("GET");
            con.setRequestProperty("Content-Type", "application/json");

            // 读取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析JSON响应
            JSONObject json = new JSONObject(response.toString());

            // 获取美式和英式音标
            JSONObject word = json.getJSONObject("ec").getJSONArray("word").getJSONObject(0);
            String usphone = word.optString("usphone", "");
            String ukphone = word.optString("ukphone", "");

            // 输出音标
            System.out.println("英[" + ukphone + "]\n美[" + usphone + "]");

            // 获取翻译列表
            JSONArray trsArray = word.getJSONArray("trs");
            StringBuilder translations = new StringBuilder();

            for (int i = 0; i < trsArray.length(); i++) {
                String translation = trsArray.getJSONObject(i).getJSONArray("tr")
                        .getJSONObject(0).getJSONObject("l").getJSONArray("i").getString(0);
                translations.append(translation).append("\n");
            }

            // 输出翻译结果
            System.out.println(translations.toString().trim());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 示例用法
        onestepget("books");
    }
}